import { Box, Grid, Button, Image, Text, VStack, HStack, Center, Badge, Heading } from '@chakra-ui/react';
import { useState, useEffect } from 'react';
import request from 'utils/request';

interface Resource {
  id: string;
  imageUrl: string;
  ownerId: string;
  isVerified: boolean;
  type: string;
  description: string;
}

// 生成模拟数据
const generateRandomAddress = () => {
  const chars = '0123456789abcdef';
  let address = '0x';
  for (let i = 0; i < 40; i++) {
    address += chars[Math.floor(Math.random() * chars.length)];
  }
  return address;
};

const generateMockResources = (seed: number): Resource[] => {
  const types = ['游戏道具', '数字艺术', '元宇宙', '收藏品', '生活实体'];
  const resources: Resource[] = [];

  for (let i = 1; i <= 30; i++) {
    // 使用确定性的方式生成数据
    const typeIndex = (i + seed) % types.length;
    const isVerified = i % 2 === 0;
    
    resources.push({
      id: generateRandomAddress().slice(0, 10),
      imageUrl: `https://picsum.photos/seed/${i}/200/200`,
      ownerId: generateRandomAddress(),
      isVerified,
      type: types[typeIndex],
      description: `这是${types[typeIndex]}，具有特殊的价值和意义。`
    });
  }
  return resources;
};

const ResourceCard = ({ resource,handleApply }: { resource: Resource,handleApply: (resource: Resource) => Promise<void> }) => {
  return (
    <Box
      borderWidth="1px"
      borderRadius="lg"
      overflow="hidden"
      bg="white"
      _hover={{ shadow: 'lg' }}
      transition="all 0.2s"
      boxShadow="sm"
      borderColor="gray.200"
    >
      <Image
        src={resource.imageUrl}
        alt={resource.id}
        height="100px"
        width="100%"
        objectFit="cover"
      />
      <VStack p={4} align="stretch" spacing={2}>
        <HStack justify="space-between">
          <Text color="gray.800" fontSize="sm" fontWeight="medium">{resource.id}</Text>
          <Badge colorScheme={resource.isVerified ? 'green' : 'gray'} px={2} py={1}>
            {resource.type}
          </Badge>
        </HStack>
        <Text fontSize="12px" color="gray.700" noOfLines={2}>
          {resource.description}
        </Text>
        <Text fontSize="xs" color="gray.600" isTruncated>
          持有者ID: {resource.ownerId}
        </Text>
        <Button
          colorScheme={resource.isVerified ? 'blue' : 'orange'}
          size="sm"
          width="full"
          onClick={() => handleApply(resource)}
          _hover={{
            transform: 'translateY(-1px)',
            shadow: 'md'
          }}
          transition="all 0.2s"
        >
          {resource.isVerified ? '交易 (已验证凭证)' : '发起认证'}
        </Button>
      </VStack>
    </Box>
  );
};

const Home = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const [resources, setResources] = useState<Resource[]>([]);
  const [isClient, setIsClient] = useState(false);
  const itemsPerPage = 25;

  useEffect(() => {
    setIsClient(true);
    setResources(generateMockResources(1));
    request.get('home/resources')
  }, []);

  const totalPages = Math.ceil(resources.length / itemsPerPage);

  const getCurrentPageResources = () => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    return resources.slice(startIndex, endIndex);
  };

  const handleApply = async (resource: Resource) => {
    if(!resource.isVerified) {
      request.get('credential/verify')
    }else{
      request.get('credential/interact')
    }
  }

  if (!isClient) {
    return null;
  }

  return (
    <>
    <Heading size="lg" marginBottom={6}>
        资源列表
      </Heading>
    <Box p={6}>
      <Grid
        templateColumns="repeat(5, 1fr)"
        gap={6}
        mb={6}
      >
        {getCurrentPageResources().map((resource) => (
          <ResourceCard key={resource.id} resource={resource} handleApply={handleApply} />
        ))}
      </Grid>

      {totalPages > 1 && (
        <Center mt={6}>
          <HStack spacing={2}>
            <Button
              size="sm"
              onClick={() => setCurrentPage(currentPage - 1)}
              isDisabled={currentPage === 1}
              colorScheme="blue"
              _hover={{
                transform: 'translateY(-1px)',
                shadow: 'md'
              }}
              transition="all 0.2s"
            >
              上一页
            </Button>
            {Array.from({ length: totalPages }, (_, i) => i + 1).map((pageNum) => (
              <Button
                key={pageNum}
                size="sm"
                onClick={() => setCurrentPage(pageNum)}
                colorScheme={currentPage === pageNum ? "blue" : "gray"}
                variant={currentPage === pageNum ? "solid" : "outline"}
                _hover={{
                  transform: 'translateY(-1px)',
                  shadow: 'md'
                }}
                transition="all 0.2s"
              >
                {pageNum}
              </Button>
            ))}
            <Button
              size="sm"
              onClick={() => setCurrentPage(currentPage + 1)}
              isDisabled={currentPage === totalPages}
              colorScheme="blue"
              _hover={{
                transform: 'translateY(-1px)',
                shadow: 'md'
              }}
              transition="all 0.2s"
            >
              下一页
            </Button>
          </HStack>
        </Center>
      )}
    </Box>
    </>
  );
};

export default Home;
